<?php
define ("SECRET", "bab99e52-922e-4c8d-9ff5-912484c21142");
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$xauth = null;
$receivedDate = null;
$headersReceived = apache_request_headers();

if (!isset($headersReceived["x-auth"])) {
	header('missing header: x-auth', true, 404);	
	echo json_encode(array("status" => false, "error" => array("message" => "Missing http header 'x-auth'", "code" => 100, "fatal" => true)));
	exit;
} else {
	$xauth = $headersReceived["x-auth"];
}
if (isset($headersReceived["date"])) {
	$receivedDate = $headersReceived["date"];
}

$diff = time() - strtotime($receivedDate);
if (($diff > 300) || ($diff < -300)) {
	header("date is more than 5 minutes from current time", true, 404);
	echo json_encode(array(
		"status" => false, 
		"error" => array("message" => "date is more than 5 minutes from current time", "code" => 102, "fatal" => true), 
		));
	exit;
}

$calculatedHMAC = base64_encode(hash_hmac("sha256", $receivedDate, SECRET));
if ($calculatedHMAC !== $xauth) {
	header("calculated hmac values do not match", true, 404);
	echo json_encode(array(
		"status" => false, 
		"error" => array("message" => "Calculated hmac values do not match", "code" => 101, "fatal" => true), 
		"data" => array("transmitted hmac" => $xauth, "server calculated hmac" => $calculatedHMAC, "header date" => $receivedDate)
		));
	exit;
}

$date = gmdate("D, d M Y H:i:s") . " GMT";
header("Date: $date");

$res = json_encode(array("ip" => $_SERVER["REMOTE_ADDR"]));

$hmac = base64_encode(hash_hmac("sha256", $date . $res, SECRET));
header("x-auth: $hmac");
echo $res;
?>
